package com.bawei.module_mine.viewmodel

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.mvi.base.BaseViewModel
import com.bawei.lib_net.entity.ResponseEntity
import com.bawei.module_mine.intent.LoginIntent
import com.bawei.module_mine.model.entity.UserEntity
import com.bawei.module_mine.model.service.UserCenterService
import com.bawei.module_mine.state.LoginState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LoginViewModel : BaseViewModel<LoginIntent>() {
    private val loginService by lazy {
        UserCenterService()
    }
    private val _state = MutableStateFlow<LoginState>(LoginState.loginInit)
    val state: StateFlow<LoginState>
        get() = _state

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect {
                when (it) {
                    is LoginIntent.Login -> doLoginIntent(it)
                }
            }
        }
    }

    private fun doLoginIntent(it: LoginIntent.Login) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                Log.d("LoginViewModel", "开始登录请求: username=${it.username}")
                val result: ResponseEntity<UserEntity> = loginService.login(it.username, it.password)
                
                withContext(Dispatchers.Main) {
                    if (result.code == 200) {
                        Log.d("LoginViewModel", "登录成功")
                        _state.value = LoginState.loginSuccess(result.data)
                    } else {
                        Log.d("LoginViewModel", "登录失败: code=${result.code}, msg=${result.msg}")
                        _state.value = LoginState.loginFailed(true)
                    }
                }
            } catch (e: Exception) {
                Log.e("LoginViewModel", "登录请求异常: ${e.message}", e)
                withContext(Dispatchers.Main) {
                    _state.value = LoginState.loginFailed(true)
                }
            }
        }
    }
}